package com.roden.study.java.math;

import org.junit.Test;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.ParsePosition;

/**
 * @Author luodeng
 * @create 2021/7/7 11:23
 */
public class BigDecimalTest {
    @Test
    public void t(){
        double a=122.599;
        System.out.println(BigDecimal.valueOf(a).longValue());
        System.out.println(BigDecimal.valueOf(a).setScale(0,BigDecimal.ROUND_HALF_UP).longValue());
    }
    @Test
    public void parse() throws ParseException {
        //  str.replace(",","")
        String str="12,949,238.30";      
        
        DecimalFormat format1 = new DecimalFormat();
        format1.setParseBigDecimal(true);
        ParsePosition position = new ParsePosition(0);
        BigDecimal value = (BigDecimal) format1.parse(str, position);
        if (str.length() == position.getIndex()) {
            System.out.println(value);
        }else {
            System.out.println("error");
        }
        //格式化解析
        DecimalFormat format2 = new DecimalFormat();       
        Number number = format2.parse(str);
        DecimalFormat dfFormat = new DecimalFormat("#.##");
        String strNumber= dfFormat.format(number);
        BigDecimal resultNumber = new BigDecimal(strNumber);
        System.out.println(resultNumber);

        //转换为逗号格式的数字
        DecimalFormat df = new DecimalFormat("#,###.00");
        String strSumNumber = df.format(resultNumber);
        System.out.println(strSumNumber); 
       
        
    }
    @Test
    public void multiplyHundred(){
        BigDecimal b1 = new BigDecimal(0);
        //movePointRight
        long start = System.currentTimeMillis();
        for(int i = 0; i <10000000; i ++){
            BigDecimal d = new BigDecimal(99);
            b1 = d.movePointRight(2);
           
        }
        long end = System.currentTimeMillis();
        System.out.println("movePointRight:" + (end -start) );
        //multiply
        start = System.currentTimeMillis();
        for(int i = 0; i <10000000; i ++){
            BigDecimal d = new BigDecimal(99);
            b1 = d.multiply(BigDecimal.TEN).multiply(BigDecimal.TEN);           
        }
        end = System.currentTimeMillis();
        System.out.println("multiply:" + (end -start) );
        //scaleByPowerOfTen
        start = System.currentTimeMillis();
        for(int i = 0; i <10000000; i ++){
            BigDecimal d = new BigDecimal(99);
            b1 = d.scaleByPowerOfTen(2);            
        }
        end = System.currentTimeMillis();
        System.out.println("scaleByPowerOfTen:" + (end -start) );
        
    }
}
